<?php

define("LIBERATIONSWEB", 20091223);

session_start();

//Librairie de fonctions
require_once(__DIR__ . '/vendor/autoload.php');
require_once("lib/libconfig.inc.php");
require_once("lib/libsession.inc.php");
require_once("lib/libfonctions.inc.php");
require_once("lib/libmysql.inc.php");
require_once("lib/libencode.inc.php");
require_once("lib/libcourriel.inc.php");
require_once("lib/libliberations.inc.php");
require_once("lib/libcentrale.inc.php");
require_once("fpdf/fpdf.php");

class PDF extends FPDF {

    var $NomEmploye;
    var $NumEmploye;
    var $PremierDeNomEmployeur;
    var $DateLiberation;
    var $Commentaire;
    var $CalculDuree;
    var $Nombre;
    var $TOperation;
    var $NoArticle;
    var $Texte24;
    var $Texte27;
    var $Texte19;
    var $Texte20;
    var $syndicatAcr;
    var $syndicatNom;
    var $configCentrale;

    function WordWrap(&$text, $maxwidth) {
        $text = trim($text);
        if ($text === '')
            return 0;
        $space = $this->GetStringWidth(' ');
        $lines = explode("\n", $text);
        $text = '';
        $count = 0;

        foreach ($lines as $line) {
            $words = preg_split('/ +/', $line);
            $width = 0;

            foreach ($words as $word) {
                $wordwidth = $this->GetStringWidth($word);
                if ($wordwidth > $maxwidth) {
                    // Word is too long, we cut it
                    for ($i = 0;
                            $i < strlen($word);
                            $i++) {
                        $wordwidth = $this->GetStringWidth(substr($word, $i, 1));
                        if ($width + $wordwidth <= $maxwidth) {
                            $width += $wordwidth;
                            $text .= substr($word, $i, 1);
                        } else {
                            $width = $wordwidth;
                            $text = rtrim($text) . "\n" . substr($word, $i, 1);
                            $count++;
                        }
                    }
                } elseif ($width + $wordwidth <= $maxwidth) {
                    $width += $wordwidth + $space;
                    $text .= $word . ' ';
                } else {
                    $width = $wordwidth + $space;
                    $text = rtrim($text) . "\n" . $word . ' ';
                    $count++;
                }
            }
            $text = rtrim($text) . "\n";
            $count++;
        }
        $text = rtrim($text);
        return $count;
    }

    // ****************************************************
    // Entête de page
    // ****************************************************
    function Header() {
        $Image41 = 'logo/' . $_SESSION["syndicatnom"] . "." . $_SESSION['logo'];
        $this->Image($Image41, 139, 25, 47, 22);

        $etiquette18 = mb_convert_encoding("Liste des libérations", 'ISO-8859-1', 'UTF-8');
        $this->SetXY(26, 26);
        $this->SetFont('Times', 'BI', 20);
        $this->Cell(114, 8, $etiquette18, 0, 0, 'L');

        $this->SetLineWidth(1);
        $this->Line(25, 50, 189, 50);

        $this->SetY(52);
    }

    // ****************************************************
    // Pied de page
    // ****************************************************
    function Footer() {
        //Numéro de page
        //Positionnement à 1,5 cm du bas
        //Police Arial italique 8
        $this->SetY(-12);
        $this->SetFont('Arial', 'I', 8);
        $this->Cell(0, 10, 'Page ' . $this->PageNo() . '/{nb}', 0, 0, 'C');

        $etiquette43 = $this->configCentrale["syndicat_nom"];
        $etiquette45 = $this->configCentrale["adresse"] . ", " . $this->configCentrale["ville"] .
                " (" . $this->configCentrale["province"] . ") " . $this->configCentrale["codepostal"] .
                " Téléphone : " . str_replace(array("(", ")"), "", $this->configCentrale["telephone"]) .
                " Télécopieur : " . str_replace(array("(", ")"), "", $this->configCentrale["telecopieur"]);

        $this->SetLineWidth(0);
        $this->Line(25, 264, 184, 264);

        $this->SetXY(25, 259);
        $this->SetFont('Times', 'B', 9);
        $this->Cell(160, 4, mb_convert_encoding($etiquette43, 'ISO-8859-1', 'UTF-8'), 0, 0, 'C');

        $this->SetXY(25, 264);
        $this->SetFont('Times', 'B', 9);
        $this->Cell(160, 4, mb_convert_encoding($etiquette45, 'ISO-8859-1', 'UTF-8'), 0, 0, 'C');
    }
}

// ****************************************************
// Ajout le total des libérations pour chaque employé
// ****************************************************
function ajoutTotalSommaireEmploye($pdf, $nombredeligne, $calculduree) {
    $pdf->SetX(29);
    $pdf->SetFont('Times', 'B', 9);
    $pdf->Cell(1, 4, mb_convert_encoding("Nombre de libérations :", 'ISO-8859-1', 'UTF-8'), 0, 0, 'L');

    $pdf->SetX(121);
    $pdf->SetFont('Times', 'B', 9);
    $pdf->Cell(1, 4, mb_convert_encoding("Durée totale :", 'ISO-8859-1', 'UTF-8'), 0, 0, 'L');

    $pdf->SetX(70);
    $pdf->SetFont('Times', 'B', 9);
    $pdf->Cell(1, 4, $nombredeligne, 0, 0, 'L');

    $pdf->SetX(154);
    $pdf->SetFont('Times', 'B', 9);
    $pdf->Cell(9, 4, sprintf("%02.2f / %dhrs", $calculduree, $calculduree * 8), 0, 0, 'R'); //1 journée correspond à 8 heures

    $pdf->ln();
}

// ****************************************************
// Ajout le total des libérations pour chaque employeur
// ****************************************************
function ajoutTotalSommaireEmployeur($pdf, $nombredeligne2, $calculduree2) {
    $pdf->SetX(29);
    $pdf->SetFont('Times', 'BU', 11);
    $pdf->Cell(1, 4, mb_convert_encoding("Nombre de libérations :", 'ISO-8859-1', 'UTF-8'), 0, 0, 'L');

    $pdf->SetX(121);
    $pdf->SetFont('Times', 'BU', 11);
    $pdf->Cell(1, 4, mb_convert_encoding("Durée totale :", 'ISO-8859-1', 'UTF-8'), 0, 0, 'L');

    $pdf->SetX(70);
    $pdf->SetFont('Times', 'BU', 11);
    $pdf->Cell(1, 4, $nombredeligne2, 0, 0, 'L');

    $pdf->SetX(154);
    $pdf->SetFont('Times', 'BU', 11);
    $pdf->Cell(9, 4, sprintf("%02.2f / %dhrs", $calculduree2, $calculduree2 * 8), 0, 0, 'R'); //1 journée correspond à 8 heures

    $pdf->ln();
    $pdf->ln();
}

// ****************************************************
//  Requête SQL principale
// ****************************************************

$i = 0;
unset($sqlparam);
$sqlparam["table"][] = "employes";
$sqlparam["table"][] = "employeurs";
$sqlparam["table"][] = "liberations";
$sqlparam["table"][] = "ligneliberations";
$sqlparam["table"][] = "articles";
$sqlparam["table"][] = "duree";
$sqlparam["join"][] = "employes.refemployeur=employeurs.refemployeur";
$sqlparam["join"][] = "employes.refemploye = liberations.refemploye";
$sqlparam["join"][] = "liberations.refliberation = ligneliberations.refliberation";
$sqlparam["join"][] = "ligneliberations.refarticle = articles.refarticle";
$sqlparam["join"][] = "duree.refduree=ligneliberations.duree";
$sqlparam["champs"][] = "CONCAT(employes.nomfamille,', ',employes.prenom) as nomemploye";
$sqlparam["champs"][] = "employes.numemploye";
$sqlparam["champs"][] = "employeurs.nomemployeur";
$sqlparam["champs"][] = "unix_timestamp(liberations.datedemande) as nombre";
$sqlparam["champs"][] = "If(liberations.typeoperation=2,'Annulation','Demande') AS toperation";
$sqlparam["champs"][] = "articles.noarticle";
$sqlparam["champs"][] = "unix_timestamp(ligneliberations.dateliberation) as dateliberation";
$sqlparam["champs"][] = "If(liberations.typeoperation=1,duree.dureeNombre,0-dureeNombre) AS calculduree";
$sqlparam["champs"][] = "employes.refemploye";
$sqlparam["champs"][] = "ligneliberations.commentaire";
$sqlparam["ordre"][] = "employeurs.nomemployeur";
$sqlparam["ordre"][] = "CONCAT(employes.nomfamille, ', ', employes.prenom)";
$sqlparam["ordre"][] = "ligneliberations.dateliberation";

require_once("lib/librapports.inc.php");

$result = executerRequeteSql($sqlparam);

// ****************************************************
// Vérification de la présence de détails dans la liste
// ****************************************************
if (!($result && is_array($result) && sizeof($result) > 0)) {
    print"<center>Aucune libérations trouvée!";
    print "<br>";
    print "<input type='button' onclick='javascript:window.close();' value='Fermer'></center>";
    die();
}

// ********************
// Traitement principal
// ********************
//Instanciation de la classe dérivée
$pdf = new PDF('P', 'mm', 'Letter');
$pdf->SetMargins(25, 25);
$pdf->AliasNbPages();
$pdf->AddPage();
$pdf->syndicatAcr = $_SESSION["syndicatnom"];
$pdf->configCentrale = buildConfigCentrale();

$nomemploye = "";
$nomemployeur = "";
$debutemploye = 0;
$debutemployeur = 0;
$calculduree = 0;
$nombredeligne = 0;
$calculduree2 = 0;
$nombredeligne2 = 0;

// *******************
// Lecture des données
// *******************
foreach ($result as $clef => $champs) {

    if ($nomemploye != $champs["nomemploye"]) {
        if ($debutemploye > 0) {
            ajoutTotalSommaireEmploye($pdf, $nombredeligne, $calculduree);
            $calculduree = 0;
            $nombredeligne = 0;
        }

        if ($nomemployeur != $champs["nomemployeur"] && $debutemployeur > 0) {
            ajoutTotalSommaireEmployeur($pdf, $nombredeligne2, $calculduree2);
            $nomemployeur = $champs["nomemployeur"];
            $calculduree2 = 0;
            $nombredeligne2 = 0;
        }

        //Ajout du nom de l'employé avec son employeur
        $NomEmploye = mb_convert_encoding($champs["nomemploye"], 'ISO-8859-1', 'UTF-8');
        $NumEmploye = $champs["numemploye"];
        $NomEmployeur = $champs["nomemployeur"];

        $pdf->SetX(25);
        $pdf->SetFillColor(199, 199, 199);
        $pdf->SetFont('Times', '', 8);
        $pdf->Cell(163, 12, " ", 0, 0, 'L', true);
        $pdf->SetFillColor(255, 255, 255);

        $pdf->SetX(25);
        $pdf->SetFont('Times', '', 8);
        $pdf->Cell(48, 4, $NomEmploye . " (" . $NumEmploye . ")", 0, 0, 'L');

        if (!isset($bHavEmployeur)) {
            $pdf->SetX(74);
            $pdf->SetFont('Times', '', 8);
            $pdf->Cell(72, 4, mb_convert_encoding($NomEmployeur, 'ISO-8859-1', 'UTF-8'), 0, 0, 'L');
        } elseif (isset($bHavEmployeur) && $bHavEmployeur && $debutemploye == 0) {
            $pdf->SetXY(25, 45);
            $pdf->SetFont('Times', 'BI', 15);
            $pdf->Cell(72, 4, mb_convert_encoding($NomEmployeur, 'ISO-8859-1', 'UTF-8'), 0, 0, 'L');
            $pdf->SetY(52);
        }

        $pdf->ln();
        $pdf->ln();

        //Détail par libérations
        $pdf->SetX(29);
        $pdf->SetFont('Times', '', 8);
        $pdf->Cell(18, 4, "Date", 0, 0, 'L');

        $pdf->SetX(52);
        $pdf->SetFont('Times', '', 8);
        $pdf->Cell(17, 4, "Type", 0, 0, 'L');

        $pdf->SetX(70);
        $pdf->SetFont('Times', '', 8);
        $pdf->Cell(12, 4, "Article", 0, 0, 'L');

        $pdf->SetX(86);
        $pdf->SetFont('Times', '', 8);
        $pdf->Cell(67, 4, "Commentaire", 0, 0, 'L');

        $pdf->SetX(154);
        $pdf->SetFont('Times', '', 8);
        $pdf->Cell(1, 4, mb_convert_encoding("Durée", 'ISO-8859-1', 'UTF-8'), 0, 0, 'L');
        $pdf->ln();

        $nomemploye = $champs["nomemploye"]; //0
    }

    $nomemployeur = $champs["nomemployeur"];
    $debutemployeur++;

    $TOperation = mb_convert_encoding($champs["toperation"], 'ISO-8859-1', 'UTF-8'); //4
    $NoArticle = mb_convert_encoding($champs["noarticle"], 'ISO-8859-1', 'UTF-8'); //5
    $DateLiberation = mb_convert_encoding(date("Y-m-d", $champs["dateliberation"]), 'ISO-8859-1', 'UTF-8'); //6
    $CDuree = mb_convert_encoding($champs["calculduree"], 'ISO-8859-1', 'UTF-8'); //7
    $Commentaire = mb_convert_encoding($champs["commentaire"], 'ISO-8859-1', 'UTF-8'); //9

    $pdf->SetX(29);
    $pdf->SetFont('Times', '', 8);
    $pdf->Cell(18, 4, $DateLiberation, 0, 0, 'L');

    $pdf->SetX(52);
    if ($TOperation == "Annulation") {
        $pdf->SetTextColor(255, 0, 0);
    }
    $pdf->SetFont('Times', '', 8);
    $pdf->Cell(17, 4, $TOperation, 0, 0, 'L');
    if ($TOperation == "Annulation") {
        $pdf->SetTextColor(0, 0, 0);
    }

    $pdf->SetX(70);
    $pdf->SetFont('Times', '', 8);
    $pdf->Cell(12, 4, $NoArticle, 0, 0, 'L');

    $pdf->SetX(154);
    if ($TOperation == "Annulation") {
        $pdf->SetTextColor(255, 0, 0);
    }
    $pdf->SetFont('Times', '', 8);
    $pdf->Cell(9, 4, sprintf("%02.2f / %dhrs", $CDuree, $CDuree * 8), 0, 0, 'R'); //1 journée correspond à 8 heures
    if ($TOperation == "Annulation") {
        $pdf->SetTextColor(0, 0, 0);
    }

    $pdf->SetX(86);
    $pdf->WordWrap($Commentaire, 67);
    $pdf->MultiCell(67, 4, $Commentaire);

    //Calcul par employé
    $calculduree = $calculduree + $CDuree;
    $nombredeligne++;

    //Calcul par employeur
    $calculduree2 = $calculduree2 + $CDuree;
    $nombredeligne2++;

    //Nombre de ligne totale
    $debutemploye++;
}

ajoutTotalSommaireEmploye($pdf, $nombredeligne, $calculduree);
ajoutTotalSommaireEmployeur($pdf, $nombredeligne2, $calculduree2);

$pdf->Output();
